import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution56 {
    public int[][] merge(int[][] intervals) {
        if(intervals == null || intervals.length == 0){
            return new int[0][];
        }
        Arrays.sort(intervals,(a, b)->a[0] - b[0]);
        List<int[]> merged = new ArrayList<>();
        merged.add(intervals[0]);
        for(int i = 1;i < intervals.length;i++){
            int[] curr = intervals[i];
            int[] last = merged.get(merged.size() - 1);
            if(curr[0] <= last[1]){
                last[1] = Math.max(last[1],curr[1]);
            }else{
                merged.add(curr);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}
